﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication5;
using System.Threading;
namespace ConsoleApplication5
{
    public class GameRules
    {
        public int FieldHeight;
        public int FieldWidth;
        public List<robot> playingRobots = new List<robot>();
        public Random rnd=new Random();
        private int targetX;
        private int targetY;

        public bool IsPositionFree(int x, int y)
        {
            return true;
        }

        public void StartGame(int FieldHeight, int FieldWidth, IEnumerable<robot> robots)
        {
            this.FieldHeight = FieldHeight;
            this.FieldWidth = FieldWidth;

            foreach(robot r in robots)
            {
                InitRobotPos(r);
            }

            PlaceTarget();
            while (IsWinnerFound() == null)
            {
                foreach (robot r in this.playingRobots)
                {
                    int CurrentRobotX=r._x;
                    int CurrentRobotY=r._y;
                    try
                    {
                        r.DoStep();
                        if (Math.Abs(r._x - CurrentRobotX) > 1 || Math.Abs(r._y - CurrentRobotY) > 1)
                        {
                            r.SetPosition(CurrentRobotX, CurrentRobotY);
                        }
                    }


                    catch
                    {
                        r.SetPosition(CurrentRobotX, CurrentRobotY);
                    }
                    r.PrintRobot();
                Thread.Sleep(500);
            }
        }
        }
    
        private void InitRobotPos(robot r)
        {
            int x=0;
            int y=0;
            do
            {
                x = rnd.Next(0, this.FieldWidth - 1);
                y = rnd.Next(0, this.FieldHeight - 1);
            }
            while (!IsPositionFree(x,y));
            
            r.SetPosition(x, y);
            this.playingRobots.Add(r);
        }
        private void PlaceTarget()
        {
            int x=0;
            int y=0;
            do
            {
                x = rnd.Next(0, this.FieldWidth - 1);
                y = rnd.Next(0, this.FieldHeight - 1);
            }
            while (IsPositionFree(x, y));
            this.targetX = x;
            this.targetY = y;
        }
        private robot IsWinnerFound()
        {
            foreach (robot r in this.playingRobots)
                if (r._x == this.targetX && r._y == this.targetY)
                    return r;

            return null;
        }
    }
}
